#!/bin/bash

# 远程服务器 Docker 安装脚本
# 适用于 CentOS 7

set -e

echo "=========================================="
echo "  Docker 安装脚本 for CentOS 7"
echo "=========================================="
echo ""

# 1. 卸载旧版本（如果存在）
echo "[1/7] 卸载旧版本 Docker..."
yum remove -y docker \
    docker-client \
    docker-client-latest \
    docker-common \
    docker-latest \
    docker-latest-logrotate \
    docker-logrotate \
    docker-engine \
    2>/dev/null || echo "未发现旧版本 Docker"

# 2. 安装必要的依赖
echo ""
echo "[2/7] 安装必要的依赖..."
yum install -y yum-utils device-mapper-persistent-data lvm2

# 3. 添加 Docker 官方仓库（使用阿里云镜像加速）
echo ""
echo "[3/7] 添加 Docker 仓库..."
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 替换仓库地址为阿里云镜像
sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo

# 4. 更新 yum 缓存
echo ""
echo "[4/7] 更新 yum 缓存..."
yum makecache fast

# 5. 安装 Docker
echo ""
echo "[5/7] 安装 Docker CE..."
yum install -y docker-ce docker-ce-cli containerd.io

# 6. 启动 Docker
echo ""
echo "[6/7] 启动 Docker 服务..."
systemctl start docker
systemctl enable docker

# 7. 配置 Docker 镜像加速（阿里云）
echo ""
echo "[7/7] 配置 Docker 镜像加速..."
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  },
  "storage-driver": "overlay2"
}
EOF

# 重启 Docker 使配置生效
systemctl daemon-reload
systemctl restart docker

# 验证安装
echo ""
echo "=========================================="
echo "  Docker 安装完成"
echo "=========================================="
echo ""
docker --version
docker info | grep -A 3 "Server Version"

echo ""
echo "✅ Docker 安装成功！"
echo ""
echo "常用命令："
echo "  - 查看版本: docker --version"
echo "  - 查看信息: docker info"
echo "  - 运行容器: docker run hello-world"
echo "  - 查看容器: docker ps -a"
echo "  - 查看镜像: docker images"
echo ""

# 测试 Docker
echo "正在测试 Docker..."
docker run --rm hello-world

echo ""
echo "🎉 Docker 测试成功！"

